const db = require('./config/database')
const fs = require('fs')
const path = require('path')

// Mock数据 - 直接在这里定义，避免前端导入问题
const mockNovels = [
  {
    id: '1',
    title: '斗破苍穹',
    author: '天蚕土豆',
    authorId: '1',
    cover:
      'https://images.unsplash.com/photo-1481627834876-b7833e8f5570?w=300&h=400&fit=crop',
    description:
      '这里是斗气大陆，没有花俏的魔法，有的，仅仅是繁衍到巅峰的斗气！在这里，斗气就是一切！',
    category: 'fantasy',
    status: 'completed',
    wordCount: 5400000,
    chapterCount: 1648,
    rating: 4.6,
    ratingCount: 89234,
    viewCount: 12500000,
    favoriteCount: 345678,
    tags: ['玄幻', '热血', '升级流', '经典'],
    isVip: true,
    price: 299,
    createdAt: '2020-03-15T08:00:00Z',
    updatedAt: '2023-08-20T15:30:00Z',
    lastChapterTitle: '大结局：斗帝归来',
    lastChapterTime: '2023-08-20T15:30:00Z'
  },
  {
    id: '7',
    title: '斗罗大陆',
    author: '唐家三少',
    authorId: '7',
    cover:
      'https://images.unsplash.com/photo-1578662996442-48f60103fc96?w=300&h=400&fit=crop',
    description:
      '唐门外门弟子唐三，因偷学内门绝学为唐门所不容，跳崖明志时却发现没有死，反而以另外一个身份来到了另一个世界，一个属于武魂的世界，名叫斗罗大陆。',
    category: 'fantasy',
    status: 'completed',
    wordCount: 8888772,
    chapterCount: 336,
    rating: 4.8,
    ratingCount: 298765,
    viewCount: 45600000,
    favoriteCount: 1234567,
    tags: ['玄幻', '武魂', '穿越', '经典', '唐家三少'],
    isVip: true,
    price: 399,
    createdAt: '2008-12-14T08:00:00Z',
    updatedAt: '2009-12-13T20:00:00Z',
    lastChapterTitle: '第三百三十六章 成神（大结局）',
    lastChapterTime: '2009-12-13T20:00:00Z'
  },
  {
    id: '2',
    title: '完美世界',
    author: '辰东',
    authorId: '2',
    cover:
      'https://images.unsplash.com/photo-1518709268805-4e9042af2176?w=300&h=400&fit=crop',
    description:
      '一粒尘可填海，一根草斩尽日月星辰，弹指间天翻地覆。群雄并起，万族林立，诸圣争霸，乱天动地。',
    category: 'fantasy',
    status: 'ongoing',
    wordCount: 6200000,
    chapterCount: 1890,
    rating: 4.8,
    ratingCount: 156789,
    viewCount: 28900000,
    favoriteCount: 567890,
    tags: ['玄幻', '无敌流', '热血', '经典'],
    isVip: true,
    price: 399,
    createdAt: '2019-05-10T10:00:00Z',
    updatedAt: '2024-01-15T09:00:00Z',
    lastChapterTitle: '第1890章：仙域风云',
    lastChapterTime: '2024-01-15T09:00:00Z'
  },
  {
    id: '3',
    title: '都市之超级医圣',
    author: '叶天南',
    authorId: '3',
    cover:
      'https://images.unsplash.com/photo-1576091160399-112ba8d25d1f?w=300&h=400&fit=crop',
    description:
      '一代医圣重生都市，凭借前世的医术和修为，在都市中纵横捭阖，谱写传奇人生。',
    category: 'urban',
    status: 'ongoing',
    wordCount: 3200000,
    chapterCount: 980,
    rating: 4.3,
    ratingCount: 45678,
    viewCount: 8900000,
    favoriteCount: 234567,
    tags: ['都市', '医术', '重生', '爽文'],
    isVip: false,
    createdAt: '2022-01-20T12:00:00Z',
    updatedAt: '2024-01-14T20:00:00Z',
    lastChapterTitle: '第980章：医者仁心',
    lastChapterTime: '2024-01-14T20:00:00Z'
  },
  {
    id: '4',
    title: '霸道总裁的小娇妻',
    author: '苏小暖',
    authorId: '4',
    cover:
      'https://images.unsplash.com/photo-1544947950-fa07a98d237f?w=300&h=400&fit=crop',
    description:
      '她是没落千金，他是商界传奇。一场意外的相遇，让两颗心紧紧相依。',
    category: 'romance',
    status: 'completed',
    wordCount: 1800000,
    chapterCount: 560,
    rating: 4.1,
    ratingCount: 23456,
    viewCount: 5600000,
    favoriteCount: 123456,
    tags: ['言情', '霸总', '甜宠', '现代'],
    isVip: true,
    price: 199,
    createdAt: '2021-06-15T14:00:00Z',
    updatedAt: '2023-12-10T16:30:00Z',
    lastChapterTitle: '大结局：幸福的开始',
    lastChapterTime: '2023-12-10T16:30:00Z'
  },
  {
    id: '5',
    title: '星际争霸之虫族崛起',
    author: '机械师',
    authorId: '5',
    cover:
      'https://images.unsplash.com/photo-1446776877081-d282a0f896e2?w=300&h=400&fit=crop',
    description:
      '穿越到星际时代，成为虫族主宰，统领无数虫族，征战星海，称霸宇宙。',
    category: 'scifi',
    status: 'ongoing',
    wordCount: 2800000,
    chapterCount: 750,
    rating: 4.5,
    ratingCount: 34567,
    viewCount: 7800000,
    favoriteCount: 189012,
    tags: ['科幻', '星际', '虫族', '征战'],
    isVip: true,
    price: 249,
    createdAt: '2022-08-01T16:00:00Z',
    updatedAt: '2024-01-13T18:00:00Z',
    lastChapterTitle: '第750章：虫族舰队',
    lastChapterTime: '2024-01-13T18:00:00Z'
  },
  {
    id: '6',
    title: '大明锦衣卫',
    author: '历史老王',
    authorId: '6',
    cover:
      'https://images.unsplash.com/photo-1578662996442-48f60103fc96?w=300&h=400&fit=crop',
    description:
      '穿越大明，成为锦衣卫，在朝堂与江湖之间游走，书写不一样的明朝传奇。',
    category: 'historical',
    status: 'ongoing',
    wordCount: 4100000,
    chapterCount: 1200,
    rating: 4.4,
    ratingCount: 67890,
    viewCount: 11200000,
    favoriteCount: 298765,
    tags: ['历史', '穿越', '锦衣卫', '朝堂'],
    isVip: false,
    createdAt: '2021-03-10T09:00:00Z',
    updatedAt: '2024-01-12T21:00:00Z',
    lastChapterTitle: '第1200章：皇城风云',
    lastChapterTime: '2024-01-12T21:00:00Z'
  }
]

const mockChapters = [
  // 斗破苍穹的章节
  {
    id: 'chapter1',
    novelId: '1',
    chapterNumber: 1,
    title: '陨落的天才',
    content:
      '斗之大陆，没有魔法，没有斗气，有的，仅仅是繁衍到巅峰的武魂！\n\n十级之后，便可凝聚斗之气旋，成为一名真正的斗者！斗之气旋，九旋巅峰，之上便是斗者九星！二星斗者，便可凝聚斗之气旋！\n\n每一旋的提升，实力便是以几何数般暴涨！\n\n而要想成为一名真正强者，必须不断的凝聚斗之气旋，并且还要经历雷劫的考验！',
    wordCount: 1580,
    isVip: false,
    price: 0,
    isFree: true,
    createdAt: '2009-04-14T10:00:00Z',
    updatedAt: '2009-04-14T10:00:00Z'
  },
  {
    id: 'chapter2',
    novelId: '1',
    chapterNumber: 2,
    title: '斗之气，三段！',
    content:
      '萧炎，萧家的少族长，曾经的天才少年，如今的废物...\n\n"斗之气，三段！级别：低级！"\n\n测验魔石碑之上，显示着萧炎如今的实力，斗之气三段，这个成绩，即便是在乌坦城之中，也足以算做是天才了！\n\n可是，看着台下众人嘲讽的目光，萧炎的心中却是一片苦涩...',
    wordCount: 2140,
    isVip: true,
    price: 0.5,
    isFree: false,
    createdAt: '2009-04-15T10:00:00Z',
    updatedAt: '2009-04-15T10:00:00Z'
  },
  // 斗罗大陆的章节
  {
    id: 'chapter7-0',
    novelId: '7',
    chapterNumber: 0,
    title: '引子',
    content:
      '唐门外门弟子唐三，因偷学内门绝学为唐门所不容，跳崖明志时却发现没有死，反而以另外一个身份来到了另一个世界，一个属于武魂的世界，名叫斗罗大陆。这里没有魔法，没有斗气，没有武术，却有神奇的武魂。',
    wordCount: 280,
    isVip: false,
    price: 0,
    isFree: true,
    createdAt: '2008-12-14T10:00:00Z',
    updatedAt: '2008-12-14T10:00:00Z'
  },
  {
    id: 'chapter7-1',
    novelId: '7',
    chapterNumber: 1,
    title: '斗罗大陆，异界唐三',
    content:
      '圣魂村是诺丁城下属的一个小村子，距离诺丁城二十里。这里民风淳朴，村民们日出而作，日落而息，过着平静的生活。\n\n在村子的最西边，有一间看上去有些破旧的铁匠铺，此时正值正午，烈日当空，但铁匠铺内却传出叮叮当当的打铁声。',
    wordCount: 2680,
    isVip: false,
    price: 0,
    isFree: true,
    createdAt: '2008-12-15T10:00:00Z',
    updatedAt: '2008-12-15T10:00:00Z'
  },
  {
    id: 'chapter7-2',
    novelId: '7',
    chapterNumber: 2,
    title: '废武魂与先天满魂力',
    content:
      '素云涛看着唐三，眼中流露出几分赞赏之色，"很好，你的武魂是蓝银草，虽然是废武魂，但你的魂力却是先天满魂力，这在魂师界是极为罕见的。"',
    wordCount: 3240,
    isVip: true,
    price: 0.5,
    isFree: false,
    createdAt: '2008-12-16T10:00:00Z',
    updatedAt: '2008-12-16T10:00:00Z'
  }
]

// 创建用户数据 - 对应作者
const mockUsers = [
  {
    id: 1,
    username: 'tudou',
    email: 'tudou@example.com',
    nickname: '天蚕土豆'
  },
  {
    id: 2,
    username: 'chendong',
    email: 'chendong@example.com',
    nickname: '辰东'
  },
  {
    id: 3,
    username: 'yetiannan',
    email: 'yetiannan@example.com',
    nickname: '叶天南'
  },
  {
    id: 4,
    username: 'suxiaonuan',
    email: 'suxiaonuan@example.com',
    nickname: '苏小暖'
  },
  {
    id: 5,
    username: 'engineer',
    email: 'engineer@example.com',
    nickname: '机械师'
  },
  {
    id: 6,
    username: 'historywang',
    email: 'historywang@example.com',
    nickname: '历史老王'
  },
  {
    id: 7,
    username: 'tangjiasanshao',
    email: 'tangjiasanshao@example.com',
    nickname: '唐家三少'
  }
]

// 作者数据 - 使用实际的表结构
const mockAuthors = [
  {
    id: 1,
    user_id: 1,
    pen_name: '天蚕土豆',
    bio: '知名玄幻小说作家，代表作《斗破苍穹》'
  },
  {
    id: 2,
    user_id: 2,
    pen_name: '辰东',
    bio: '玄幻小说大神，代表作《完美世界》'
  },
  { id: 3, user_id: 3, pen_name: '叶天南', bio: '都市小说作者' },
  { id: 4, user_id: 4, pen_name: '苏小暖', bio: '言情小说作者' },
  { id: 5, user_id: 5, pen_name: '机械师', bio: '科幻小说作者' },
  { id: 6, user_id: 6, pen_name: '历史老王', bio: '历史小说作者' },
  {
    id: 7,
    user_id: 7,
    pen_name: '唐家三少',
    bio: '网文大神，代表作《斗罗大陆》'
  }
]

;(async () => {
  try {
    console.log('🚀 开始迁移Mock数据到数据库...')

    // 1. 清空现有数据（按外键依赖顺序）
    console.log('📭 清空现有数据...')
    await db.query('DELETE FROM chapters')
    await db.query('DELETE FROM novels')
    await db.query('DELETE FROM authors')
    await db.query('DELETE FROM users WHERE id IN (1,2,3,4,5,6,7)') // 只删除作者用户
    console.log('✅ 清空完成')

    // 2. 插入用户数据（作者用户）
    console.log('👤 插入用户数据...')
    for (const user of mockUsers) {
      await db.query(
        `
        INSERT INTO users (id, username, email, nickname, password_hash, role, created_at) 
        VALUES (?, ?, ?, ?, ?, 'user', NOW())
      `,
        [
          user.id,
          user.username,
          user.email,
          user.nickname,
          '$2b$10$dummy.hash.for.demo.user' // 临时密码hash
        ]
      )
      console.log(`   ✓ 用户: ${user.nickname} (${user.username})`)
    }
    console.log(`✅ 成功插入 ${mockUsers.length} 个用户`)

    // 3. 插入作者数据
    console.log('👨‍💼 插入作者数据...')
    for (const author of mockAuthors) {
      await db.query(
        `
        INSERT INTO authors (id, user_id, pen_name, bio, created_at) 
        VALUES (?, ?, ?, ?, NOW())
      `,
        [author.id, author.user_id, author.pen_name, author.bio]
      )
      console.log(`   ✓ 作者: ${author.pen_name}`)
    }
    console.log(`✅ 成功插入 ${mockAuthors.length} 个作者`)

    // 4. 插入小说数据
    console.log('📚 插入小说数据...')
    for (const novel of mockNovels) {
      await db.query(
        `
        INSERT INTO novels (
          id, title, author_id, description, cover_url, category, 
          tags, status, word_count, chapter_count, rating, rating_count,
          view_count, favorite_count, is_vip, price_per_chapter, 
          created_at, updated_at
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
      `,
        [
          novel.id,
          novel.title,
          novel.authorId,
          novel.description,
          novel.cover,
          novel.category,
          JSON.stringify(novel.tags),
          novel.status === 'completed' ? 'completed' : 'ongoing',
          novel.wordCount,
          novel.chapterCount,
          novel.rating,
          novel.ratingCount,
          novel.viewCount,
          novel.favoriteCount,
          novel.isVip ? 1 : 0,
          novel.price / 100 || 0, // 转换为元
          new Date(novel.createdAt),
          new Date(novel.updatedAt)
        ]
      )
      console.log(`   ✓ 小说: ${novel.title} (${novel.author})`)
    }
    console.log(`✅ 成功插入 ${mockNovels.length} 本小说`)

    // 5. 插入章节数据
    console.log('📄 插入章节数据...')
    for (const chapter of mockChapters) {
      await db.query(
        `
        INSERT INTO chapters (
          novel_id, title, content, chapter_number, word_count, 
          is_vip, price, view_count, created_at, updated_at
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
      `,
        [
          chapter.novelId,
          chapter.title,
          chapter.content,
          chapter.chapterNumber,
          chapter.wordCount,
          chapter.isVip ? 1 : 0,
          chapter.price || 0,
          0, // 初始浏览量为0
          new Date(chapter.createdAt),
          new Date(chapter.updatedAt)
        ]
      )
      console.log(`   ✓ 章节: ${chapter.title} (小说ID: ${chapter.novelId})`)
    }
    console.log(`✅ 成功插入 ${mockChapters.length} 个章节`)

    // 6. 验证数据
    console.log('🔍 验证插入的数据...')
    const userCount = await db.query(
      'SELECT COUNT(*) as count FROM users WHERE id BETWEEN 1 AND 7'
    )
    const authorCount = await db.query('SELECT COUNT(*) as count FROM authors')
    const novelCount = await db.query('SELECT COUNT(*) as count FROM novels')
    const chapterCount = await db.query(
      'SELECT COUNT(*) as count FROM chapters'
    )

    console.log(`📊 数据统计:`)
    console.log(`   - 用户: ${userCount[0].count} 个`)
    console.log(`   - 作者: ${authorCount[0].count} 个`)
    console.log(`   - 小说: ${novelCount[0].count} 本`)
    console.log(`   - 章节: ${chapterCount[0].count} 个`)

    // 显示几个示例小说
    const sampleNovels = await db.query(`
      SELECT n.title, a.pen_name as author, n.category, n.view_count, n.favorite_count 
      FROM novels n
      JOIN authors a ON n.author_id = a.id
      ORDER BY n.view_count DESC 
      LIMIT 3
    `)

    console.log(`\n🌟 热门小说预览:`)
    sampleNovels.forEach(novel => {
      console.log(`   📖 ${novel.title} - ${novel.author} (${novel.category})`)
      console.log(
        `      浏览: ${novel.view_count.toLocaleString()}, 收藏: ${novel.favorite_count.toLocaleString()}`
      )
    })

    console.log('\n🎉 Mock数据迁移完成！')
    console.log('\n💡 接下来需要修改前端代码，将API调用从Mock数据切换到真实API')
  } catch (error) {
    console.error('❌ 迁移失败:', error.message)
    console.error('详细错误:', error)
  }

  process.exit()
})()
